package tech.dongliang.baidu.ueditor.upload;

import tech.dongliang.baidu.ueditor.PathFormat;
import tech.dongliang.baidu.ueditor.define.AppInfo;
import tech.dongliang.baidu.ueditor.define.BaseState;
import tech.dongliang.baidu.ueditor.define.FileType;
import tech.dongliang.baidu.ueditor.define.State;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Slf4j
public class BinaryUploader {
    public static final State save(HttpServletRequest request, Map<String, Object> conf) {
        String filedName = (String) conf.get("fieldName");
        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        try {
            State storageState = null;
            boolean compress = false;
            //获取上传文件
            MultipartFile file = multipartRequest.getFile(filedName);
            if (file == null) {
                return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
            }
            //获取上传路径
            String savePath = (String) conf.get("savePath");
            //上传源文件名
            String originFileName = file.getOriginalFilename();
            //上传文件后缀
            String suffix = FileType.getSuffixByFilename(originFileName);
            originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
            savePath = savePath + suffix;
            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
            }
            savePath = PathFormat.parse(savePath, originFileName);
            String physicalPath = conf.get("basePath") + savePath;


            //此处添加水印
            //FileUtil.pressImage(physicalPath, propertyUtil.getProperty("file.root")+"logopng.png", 1, 1, 0.7f);//加水印
            //是否压缩
            if ((boolean) conf.get("imageCompressEnable")) {
                int width = (int) conf.get("imageCompressBorder");
                BufferedImage srcImgBuff = ImageIO.read(file.getInputStream());
                if (srcImgBuff.getWidth() > width) {
                    suffix = ".jpg";
                    savePath = FilenameUtils.removeExtension(savePath) + suffix;
                    File destFile = new File(conf.get("basePath") + savePath);
                    if (!destFile.getParentFile().exists()) {
                        destFile.getParentFile().mkdirs();
                    }
                    Thumbnails.of(srcImgBuff).outputFormat("jpg").size(width, srcImgBuff.getHeight()).toFile(destFile);
                    compress = true;
                    storageState = new BaseState(true);
                }
            }
            if (!compress) {
                long maxSize = ((Long) conf.get("maxSize")).longValue();
                InputStream is = file.getInputStream();
                storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
                is.close();
            }
            File targetFile = new File(conf.get("basePath") + savePath);
            storageState.putInfo("size", targetFile.length());
            storageState.putInfo("title", targetFile.getName());
            storageState.putInfo("url", PathFormat.format(savePath));
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", originFileName + suffix);
            return storageState;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return new BaseState(false, AppInfo.IO_ERROR);
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);

        return list.contains(type);
    }
}
